package com.audi.activity;

import java.util.ArrayList;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Typeface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.SpannableStringBuilder;
import android.text.style.StyleSpan;
import android.text.style.TypefaceSpan;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.audi.R;
import com.audi.BaseActivity;
import com.audi.adapter.AddDeviceViewPagerAdapter;
import com.audi.adapter.ListPlaceDialogAdapter;
import com.audi.adapter.SQLiteAsusNewHelper;
import com.audi.dto.DeviceItem;
import com.audi.dto.PlaceItem;
import com.audi.message.ActionMessage;
import com.audi.message.SendMessage;
import com.audi.view.AudiDialog;
import com.audi.view.BaseDeviceDialog;
import com.audi.view.BasePlaceDialog;

public class NewDeviceActivity extends BaseActivity {
	// private ImageView imvPage1, imvPage2, imvPage3, imvPage4, img_staus;
	private AddDeviceViewPagerAdapter mAdapter;
	// private ViewPager mViewPager;
	private ImageView mStatusDeviceReady, mStatusDeviceReadyAnimation,
			img_staus;
	private boolean statusReady = true;
	public ArrayList<PlaceItem> mListPlaceCard;
	private EditText createNewDeviceEdit;
	public DeviceItem newDeviceItem = new DeviceItem();
	public SendMessage sendMessage = new SendMessage();
	private TextView txt_status;
	private FrameLayout framePhysical, frameNext;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_new_device);
		initActionBar(R.layout.action_bar_add_new_device);
		initView();

		// dumpDataPlaceCard();
		initListener();
		// ShowAlarmSensor();
	}

	/**
	 * apply for test
	 */
	private void initView() {

		framePhysical = (FrameLayout) findViewById(R.id.frame_physical);
		frameNext = (FrameLayout) findViewById(R.id.frame_next_step);
		mStatusDeviceReady = (ImageView) findViewById(R.id.img_add_new_device_button);
		mStatusDeviceReadyAnimation = (ImageView) findViewById(R.id.img_add_new_device_button_ready);
		txt_status = (TextView) findViewById(R.id.txt_status);
		img_staus = (ImageView) findViewById(R.id.img_add_new_device_status);
		frameNext.setVisibility(View.INVISIBLE);
		framePhysical.setVisibility(View.INVISIBLE);
		img_staus.setVisibility(View.VISIBLE);
		mStatusDeviceReadyAnimation.setVisibility(View.INVISIBLE);
		mStatusDeviceReady.setVisibility(View.VISIBLE);
		SpannableStringBuilder text = new SpannableStringBuilder(
				"1. Press Button to start connection of Home Box.");
		text.setSpan(new StyleSpan(android.graphics.Typeface.BOLD), 0, 2, 0);
		txt_status.setText(text);
		txt_status.setText(text);

	}

	private void initListener() {
		frameNext.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View view) {

				// mStatusDeviceReady.setVisibility(View.INVISIBLE);

				if (statusReady) {
					// 2.2.2 New device connectionName new device

					final AudiDialog dialogNewDevice = new AudiDialog(
							NewDeviceActivity.this);
					dialogNewDevice.setLayout(R.layout.new_device_dialog);
					dialogNewDevice.show();
					Button skip = (Button) dialogNewDevice
							.findViewById(R.id.btn_new_device_dialog_skip);
					Button next = (Button) dialogNewDevice
							.findViewById(R.id.btn_new_device_dialog_next);
					final EditText nameDeviceEdit = (EditText) dialogNewDevice
							.findViewById(R.id.edit_new_device_dialog_input);
					// nameDeviceEdit.setHint(R.string.create_device_hint);
					nameDeviceEdit.setText("");
					nameDeviceEdit.setSelection(nameDeviceEdit.getText()
							.length());
					skip.setOnClickListener(new OnClickListener() {

						@Override
						public void onClick(View arg0) {
							dialogNewDevice.dismiss();
						}
					});
					next.setOnClickListener(new OnClickListener() {
						@Override
						public void onClick(View v) {
							if (nameDeviceEdit.length() > 0) {

								newDeviceItem.setDeviceName(nameDeviceEdit
										.getText().toString() + "");
								newDeviceItem.setUserId(1);
								newDeviceItem.setDeviceType(1);
								newDeviceItem.setDeviceStatus(0);
								newDeviceItem.setIscheck(true);
								newDeviceItem.setIsDeleted(0);
								newDeviceItem.setFavorite(0);
								newDeviceItem.setCapability(1);
								newDeviceItem.setDeviceCode("dasdasdas");
								dialogNewDevice.dismiss();
								BaseDeviceDialog addNewplaceDialog = new BaseDeviceDialog(
										NewDeviceActivity.this);
								addNewplaceDialog.showSelectPlaceDialogAddNew(
										newDeviceItem, addDeviceFinishHandler);
							} else {
								Toast.makeText(getApplicationContext(),
										"Input device name", 1).show();
							}
						}
					});
				} else {
					// 2-2-2-3 Notice Dialog
					final AudiDialog dialogNoteDevice = new AudiDialog(
							NewDeviceActivity.this, R.style.CustomDialogTheme);
					dialogNoteDevice.setLayout(R.layout.notice_device_dialog);
					dialogNoteDevice.show();
					Button no = (Button) dialogNoteDevice
							.findViewById(R.id.note_device_dialog_no);
					Button yes = (Button) dialogNoteDevice
							.findViewById(R.id.note_device_dialog_yes);

					no.setOnClickListener(new OnClickListener() {

						@Override
						public void onClick(View arg0) {
							dialogNoteDevice.dismiss();
						}
					});
					yes.setOnClickListener(new OnClickListener() {

						@Override
						public void onClick(View v) {

							dialogNoteDevice.dismiss();
							finish();
						}
					});
				}
			}
		});

		mStatusDeviceReady.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub

				txt_status.setText("Connecting....");
				mStatusDeviceReady.setVisibility(View.INVISIBLE);
				mStatusDeviceReadyAnimation.setVisibility(View.VISIBLE);

			}
		});

		mStatusDeviceReadyAnimation.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub

				framePhysical.setVisibility(View.VISIBLE);

				frameNext.setVisibility(View.VISIBLE);
				mStatusDeviceReadyAnimation.setVisibility(View.INVISIBLE);
				SpannableStringBuilder text = new SpannableStringBuilder(
						"2. Press Physical Button on Device.");
				text.setSpan(new StyleSpan(android.graphics.Typeface.BOLD), 0,
						2, 0);
				txt_status.setText(text);
			}
		});
	}

	// 2-2-3 New device connectionSelect a place for the device
	public void showSelectPlaceDialog() {

		// Get list place

		sendMessage.sendData(ActionMessage.getAllPlaceList, null,
				loadListPlaceHandler);

	}

	public void selectPlace(final AudiDialog selectPlaceDevice) {

		ListView placeList = (ListView) selectPlaceDevice
				.findViewById(R.id.list_place_dialog);
		ListPlaceDialogAdapter placeAdapter = new ListPlaceDialogAdapter(
				NewDeviceActivity.this, mListPlaceCard);
		placeList.setAdapter(placeAdapter);
		LinearLayout llSelectNewPlaceDialog = (LinearLayout) selectPlaceDevice
				.findViewById(R.id.ll_select_new_place_dialog);
		Button btnSkip = (Button) selectPlaceDevice
				.findViewById(R.id.btn_cancle_dialog);
		btnSkip.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				selectPlaceDevice.dismiss();

			}
		});
		llSelectNewPlaceDialog.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// showSelectStatusPlace();
				BaseDeviceDialog addNewplaceDialog = new BaseDeviceDialog(
						getApplicationContext());
				/*
				 * addNewplaceDialog .showSelectPlaceDialog(deviceItem,
				 * handlerUpdateDevice);
				 */

				// finish();
			}
		});
		placeList.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {

				PlaceItem newIemPlace = new PlaceItem();
				newIemPlace = (PlaceItem) arg0.getItemAtPosition(arg2);

				newDeviceItem.setDevicePlaceId(newIemPlace.getPlaceId());
				newDeviceItem.setDevicePlace(newIemPlace.getPlaceName());

				sendMessage.sendData(ActionMessage.addDevice, newDeviceItem,
						addDeviceFinishHandler);

				// finish();
			}
		});
	}

	@SuppressLint("HandlerLeak")
	// add device
	private Handler addDeviceFinishHandler = new Handler() {

		public void handleMessage(final Message msg) {
			runOnUiThread(new Runnable() {
				public void run() {
					try {
						if (msg.arg1 != -1) {
							int de = msg.getData().getInt(
									String.valueOf(ActionMessage.addDevice));
							if (de > 0) {

								Intent intentDeviceCard = new Intent(
										getApplicationContext(),
										DeviceDetailActivity.class);
								Bundle bundleInfoDevice = new Bundle();
								bundleInfoDevice.putSerializable("item",
										newDeviceItem);
								intentDeviceCard.putExtras(bundleInfoDevice);
								startActivity(intentDeviceCard);
								finish();
							} else {
								Log.d("add device fail",
										"1--------------------");
							}
						}
					} catch (Exception e) {

						Log.d("add device fail", "2--------------------");
						finish();
						// CreateWarningDialog("them that bai");
					}
				}
			});
		}
	};
	@SuppressLint("HandlerLeak")
	private Handler loadListPlaceHandler = new Handler() {

		public void handleMessage(final Message msg) {
			runOnUiThread(new Runnable() {
				public void run() {
					try {
						if (msg.arg1 != -1) {
							@SuppressWarnings("unchecked")
							ArrayList<PlaceItem> result = (ArrayList<PlaceItem>) msg
									.getData()
									.getSerializable(
											String.valueOf(ActionMessage.getAllPlaceList));
							if (result.size() > 0) {
								mListPlaceCard = result;

								final AudiDialog selectPlaceDevice = new AudiDialog(
										NewDeviceActivity.this);
								selectPlaceDevice
										.setLayout(R.layout.select_place_dialog);
								selectPlaceDevice.show();
								// load data placecard
								TextView titlePlace = (TextView) selectPlaceDevice
										.findViewById(R.id.txt_select_place_title);
								titlePlace.setText(R.string.select_place_title);
								selectPlace(selectPlaceDevice);
							} else {
								Log.d("Load Place Fail",
										"1-------------------fail ");
							}
						} else {
							Log.d("Load Place Fail",
									"2-------------------fail ");

						}
					} catch (Exception e) {
					}
				}
			});
		}
	};

	// 3-1-2-2 Select public/privateTap
	public void showSelectStatusPlace() {
		final AudiDialog selectStatusPlace = new AudiDialog(
				NewDeviceActivity.this);
		selectStatusPlace.setLayout(R.layout.select_capability);
		selectStatusPlace.show();
		TextView txtPrivate = (TextView) selectStatusPlace
				.findViewById(R.id.text_private);
		TextView txtPublic = (TextView) selectStatusPlace
				.findViewById(R.id.text_public);
		txtPrivate.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				showNewDeviceDialog();
				selectStatusPlace.dismiss();
			}
		});
		txtPublic.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				showNewDeviceDialog();
				selectStatusPlace.dismiss();
			}
		});
	}

	//
	public void showNewDeviceDialog() {
		final AudiDialog newDevcieDialog = new AudiDialog(
				NewDeviceActivity.this);
		newDevcieDialog.setLayout(R.layout.new_device_dialog);
		newDevcieDialog.show();
		TextView createNewPlaceTitle = (TextView) newDevcieDialog
				.findViewById(R.id.txt_new_device_dilog_title);
		TextView createNewPlaceHint = (TextView) newDevcieDialog
				.findViewById(R.id.txt_new_device_dilog_hint);
		createNewDeviceEdit = (EditText) newDevcieDialog
				.findViewById(R.id.edit_new_device_dialog_input);
		Button cancleBtn = (Button) newDevcieDialog
				.findViewById(R.id.btn_new_device_dialog_skip);
		Button okBtn = (Button) newDevcieDialog
				.findViewById(R.id.btn_new_device_dialog_next);
		createNewDeviceEdit.setHint(R.string.create_device_hint);
		createNewDeviceEdit.setText("");
		createNewPlaceTitle.setText(R.string.create_place_title);
		createNewPlaceHint.setVisibility(View.GONE);
		cancleBtn.setText(R.string.cancel);
		okBtn.setText(R.string.ok);
		okBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				newDevcieDialog.dismiss();
				showNoticePlace();
			}
		});
		cancleBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				newDevcieDialog.dismiss();
			}
		});
	}

	// 3-1-2-4 Notice Dialog
	public void showNoticePlace() {
		final AudiDialog noticeDialog = new AudiDialog(NewDeviceActivity.this);
		noticeDialog.setLayout(R.layout.notice_device_dialog);
		noticeDialog.show();
	}

	// 2-3-4 Automatically add default actions with warning sensors
	public void showAlarmSensor() {
		final AudiDialog alarmSensorDialog = new AudiDialog(
				NewDeviceActivity.this, R.style.CustomDialogTheme);
		alarmSensorDialog.setLayout(R.layout.alarm_sensor_dialog);
		alarmSensorDialog.show();
		Button alert = (Button) alarmSensorDialog
				.findViewById(R.id.alarm_sensor_dialog_ok);
		alert.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				alarmSensorDialog.dismiss();
			}
		});
		ListView listWarning = (ListView) alarmSensorDialog
				.findViewById(R.id.alarm_sensor_dialog_warning_list);
		ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
				android.R.layout.simple_list_item_1, getResources()
						.getStringArray(R.array.dialog_alarm_sensor_warning));
		listWarning.setAdapter(adapter);
	}

	@Override
	public void onRefreshData() {
		// TODO Auto-generated method stub

	}
}
